package com.wxl.common.http

import android.os.Handler
import android.os.Looper
import android.os.Message

class SerialHttpHandler<T> {

    private val mHandler = object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    mSerialHttpCallback.error(msg.obj as Throwable)
                }
                2 -> {
                    mSerialHttpCallback.loadDataSuccess(msg.obj as T)
                }
                3->{
                    mSerialHttpCallback.loadDataSuccess(msg.obj as ArrayList<T>)
                }
            }
        }
    }

    private var mSerialHttpCallback:SerialHttpCallback<T>

    constructor(mSerialHttpCallback: SerialHttpCallback<T>) {
        this.mSerialHttpCallback = mSerialHttpCallback
    }

    fun sendError(e: Throwable){
        val message = mHandler.obtainMessage()
        message.obj = e
        message.what = 1
        mHandler.sendMessage(message)
    }

    fun sendSuccess(data:T?){
        val message = mHandler.obtainMessage()
        message.obj = data
        message.what = 2
        mHandler.sendMessage(message)
    }

    fun sendSuccess(datas:ArrayList<T>?){
        val message = mHandler.obtainMessage()
        message.obj = datas
        message.what = 3
        mHandler.sendMessage(message)
    }

    fun release(){
        mHandler.removeCallbacksAndMessages(0)
    }
}